import { getBaseUrl, requestUtil } from '../../utils/requestUtil.js'
import regeneratorRuntime from "../../lib/runtime/runtime"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    baseUrl: '',
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },

  address: {
    cityName: "广州市",
    countyName: "海珠区",
    detailInfo: "新增中路",
    errMsg: "chooseAddress:ok",
    nationalCode: "510000",
    postalCode: "510000",
    provinceName: "广东省",
    telNumber: "13412341234",
    userName: "张三"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const baseUrl = getBaseUrl();
    this.setData({
      baseUrl
    })
  },

  handleChooseAddress() {
    wx.chooseAddress({
      success (result) {
        console.log(result)
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.setStorageSync('address', this.address)
    const address = wx.getStorageSync('address')
    const cart = wx.getStorageSync('cart') || []
   
    this.setData({
      address
    })

    this.setCart(cart)
  },

  handleItemChange(e) {
    const { id } = e.currentTarget.dataset
    let { cart } = this.data
    let index = cart.findIndex(item => item.id === id)
    cart[index].checked = !cart[index].checked
    
    this.setCart(cart)
  },

  setCart(cart) {
    let allChecked = true
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(item => {
      if (item.checked) {
        totalNum += item.num
        totalPrice += item.price * item.num
      } else {
        allChecked = false
      }
    })
    allChecked = cart.length != 0 ? allChecked : false
    this.setData({
      cart,
      allChecked,
      totalNum,
      totalPrice
    })
    wx.setStorageSync('cart', cart)
  },

  handleItemAllCheck() {
    let { cart, allChecked } = this.data
    allChecked = !allChecked
    cart.forEach(item => item.checked = allChecked)
    this.setCart(cart)
  },
  
  handleItemNumEdit(e) {
    const { id, operation } = e.currentTarget.dataset
    let { cart } = this.data
    let index = cart.findIndex(item => item.id === id)
    if (cart[index].num === 1 && operation=== -1) {
      wx.showModal({
        title: '系统提示',
        content: '您是否要删除?',
        cancelColor: 'cancelColor',
        success: (res) => {
          if (res.confirm) {
            cart.splice(index, 1)
            this.setCart(cart)
          }
        }
      })
    } else {
      cart[index].num += operation
      this.setCart(cart)
    }
  },

  handlePay() {
    const { address, totalNum } = this.data
    if (!address) {
      wx.showToast({
        title: '您还没有选择收货地址',
        icon: 'none'
      })
      return
    }
    if (totalNum === 0) {
      wx.showToast({
        title: '您还没有选购商品',
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: '/pages/pay/index',
    })
  }
})